export const keyword = 'user';

// 获取数据，base64解码->url解码
export const getData = key =>
  JSON.parse(
    decodeURI(atob(localStorage.getItem(`${keyword}-${key}`) || '') || '') ||
      '[]'
  );

// 设置数据
export const setData = (key, value) => {
  return localStorage.setItem(
    `${keyword}-${key}`,
    // url编码->base64编码
    btoa(encodeURI(JSON.stringify(value || [])))
  );
};
// 删除数据
export const deleteData = key => localStorage.removeItem(`${keyword}-${key}`);

// 获取上次登录者数据
export const lastLoginUser = () => {
  const uname = Object.keys(localStorage)
    .filter(it => it.startsWith(keyword))
    .find(it => getData(it?.replace?.(`${keyword}-`, '')).lastLogin)
    ?.replace?.(`${keyword}-`, '');
  const userInfo = getData(uname);
  userInfo.name = uname;
  return userInfo;
};

// 重置本地数据，把lastLogin改为false
export const resetLogin = () =>
  Object.keys(localStorage)
    .filter(it => it.startsWith(keyword))
    .forEach(it => {
      const resetData = getData(it.replace(`${keyword}-`, ''));
      resetData.lastLogin = false;

      setData(it?.replace?.(`${keyword}-`, ''), resetData);
    });
